package org.jhh.trigger.job;

import cn.bugstack.middleware.db.router.strategy.IDBRouterStrategy;
import lombok.extern.slf4j.Slf4j;
import org.jhh.domain.task.model.entity.TaskEntity;
import org.jhh.domain.task.service.ITaskService;
import org.jhh.domain.task.service.TaskService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component()
public class SendMessageTaskJob {
    @Resource
    private ThreadPoolTaskScheduler executor;

    @Resource
    private IDBRouterStrategy dbRouter;

    @Resource
    private ITaskService taskService;

    @Scheduled(cron = "0/5 * * * * ?")
    public void exec(){
//        主要作用是发送发送·失败了的消息 达到最终一致性 记得用线程池去加速
        try{
//      遍历表 查找没有成功发送的消息
            int dbCount = dbRouter.dbCount();
            for(int i= 1;i<=dbCount;i++){
                int finalDbIdx = i;
                executor.execute(()->{
                    try{
                        dbRouter.setDBKey(finalDbIdx);
                        dbRouter.setTBKey(0);
                        List<TaskEntity> taskEntities = taskService.queryNoSendMessageTaskList();
                        if(taskEntities.isEmpty()){return;}
                        for(TaskEntity taskEntity : taskEntities){
                            executor.execute(()->{
                                try {
                                       taskService.sendMessage(taskEntity);
                                       taskService.updateTaskSendMessageCompleted(taskEntity.getUserId(), taskEntity.getMessageId());
                                }catch (Exception e){
                                    log.error("定时任务，发送MQ消息失败 userId: {} topic: {}", taskEntity.getUserId(), taskEntity.getTopic());
                                    taskService.updateTaskSendMessageFail(taskEntity.getUserId(), taskEntity.getMessageId());
                                }
                            });
                        }
                    } finally {
                        dbRouter.clear();
                    }
                });
            }
        }catch (Exception e){
            log.error("定时任务，扫描MQ任务表发送消息失败。", e);
        }finally {
            dbRouter.clear();
        }
    }
}
